﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using ibba.src.noriskbo.Models;
using System.Windows.Documents;
using System.Collections.Generic;
using ibba.src.noriskbo.ViewModels;
using ibba.src.noriskbo.code.translate;
using Infragistics.Documents.Excel;
using System.Windows.Resources;


namespace ibba.src.noriskbo
{
    public partial class PageExportacaoPortfolio : ChildWindow
    {

        #region Atributos

        private PageExportacaoPortfolioPresenter _pageExportacaoPortfolioPresenter;

        private List<Portfolio> _listaPortfolio;

        private Stream _stream;

        #endregion

        #region Métodos

        public PageExportacaoPortfolio()
        {
            InitializeComponent();

            _pageExportacaoPortfolioPresenter = new PageExportacaoPortfolioPresenter();

            CarregarBarraBotoes();

            dpDtBase.SelectedDate = DateTime.Now.Date;
        }

        private void CarregarBarraBotoes()
        {
            barraMenu.ClearButtons();

            barraMenu.AddNewButton(Constantes.SourceImagem.BOTAO_APROVAR.ToString(), "Confirmar", Constantes.SourceImagem.BOTAO_APROVAR, 1, btnConfirmar);
            barraMenu.AddNewButton(Constantes.SourceImagem.BOTAO_REJEITAR.ToString(), "Cancelar", Constantes.SourceImagem.BOTAO_REJEITAR, 2, btnCancelar);

            barraMenu.AlterarVisibilidadeBotao(Constantes.SourceImagem.BOTAO_APROVAR.ToString(), false);
        }

        private void btnConfirmar()
        {
            SaveFileDialog savefileDialog = new SaveFileDialog { Filter = "Excel files|*.xls", DefaultExt = "xls" };

            if (savefileDialog.ShowDialog() == true)
            {
                _stream = savefileDialog.OpenFile();
                _pageExportacaoPortfolioPresenter.ObterPortfoliosPorDataVigencia(dpDtBase.SelectedDate.Value.Date, ObterPortfoliosPorDataVigenciaCallBack);
                StartBusy();
            }

        }

        private void ObterPortfoliosPorDataVigenciaCallBack(IAsyncResult pAsyncResult)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                try
                {
                    _listaPortfolio = PortfolioTL.TranslatePortfolioDCToPortfolio(((ServicePortfolio.IServicePortfolioAdmin)pAsyncResult.AsyncState).EndObterPortfoliosPorDataVigencia(pAsyncResult));
                    ExportarPortfolios();
                }
                catch (Exception ex)
                {
                    MessageBoxHelper.ShowErro("Atenção!", "Erro ao executar o metodo ObterPortfoliosPorDataVigencia!", ex.Message);
                    EndBusy();
                }

            });
        }

        private void ExportarPortfolios()
        {
            try
            {
                Workbook excelFile = new Workbook(Infragistics.Documents.Excel.WorkbookFormat.Excel97To2003);

                excelFile.Worksheets.Add("Layout");
                //excelFile.Worksheets[0].Rows[0].Cells[0].Value = "DATA";

                excelFile.Worksheets[0].Rows[0].Cells[0].Value = "DATA_INICIO_VIG";
                excelFile.Worksheets[0].Rows[0].Cells[1].Value = "DATA_FIM_VIG";
                excelFile.Worksheets[0].Rows[0].Cells[2].Value = "CGI_CLIENTE";
                excelFile.Worksheets[0].Rows[0].Cells[3].Value = "ID_VEICULO_LEGAL";
                excelFile.Worksheets[0].Rows[0].Cells[4].Value = "NM_CLIENTE";
                excelFile.Worksheets[0].Rows[0].Cells[5].Value = "NM_VEICULO_LEGAL";
                excelFile.Worksheets[0].Rows[0].Cells[6].Value = "THRESHOLD (R$)";
                excelFile.Worksheets[0].Rows[0].Cells[7].Value = "MTA (R$)";
                excelFile.Worksheets[0].Rows[0].Cells[8].Value = "PRAZO VERIFIC (DC)";
                excelFile.Worksheets[0].Rows[0].Cells[9].Value = "HAIRCUT (%)";
                excelFile.Worksheets[0].Rows[0].Cells[10].Value = "ID_ISDA";
                excelFile.Worksheets[0].Rows[0].Cells[11].Value = "MOEDA";

                excelFile.Worksheets.Add("Margem");

                //excelFile.Worksheets[1].Rows[0].Cells[0].Value = "DATA";
                excelFile.Worksheets[1].Rows[0].Cells[0].Value = "ID_ISDA";
                excelFile.Worksheets[1].Rows[0].Cells[1].Value = "MARGEM DEPOSITADA (R$)";

                List<PortfolioCliente> listaCliente;
                string maxNomeCliente = "";

                int contRowLayout = 0;
                int contRowMargem = 0;



                if (_listaPortfolio.Count > 0)
                {
                    _listaPortfolio.ForEach(l =>
                        {
                            listaCliente = new List<PortfolioCliente>();

                            foreach (var c in l.ListaClientes)
                            {
                                if (listaCliente.Count(lc => (lc.NoCnpjCpf == c.NoCnpjCpf)
                                                             && (lc.IdVeiculoLegal == c.IdVeiculoLegal)) == 0)
                                {
                                    contRowLayout++;

                                    //excelFile.Worksheets[0].Rows[contRowLayout].Cells[0].Value = l.dtPortfolio.ToString("dd/MM/yyyy");

                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[0].Value = l.DtIniVig;


                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[1].Value = (l.DtFimVig == DateTime.MinValue) ? null : l.DtFimVig;
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[2].Value = c.NoCnpjCpf;
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[3].Value = c.IdVeiculoLegal;
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[4].Value = c.NomeCliente.Trim();
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[5].Value = c.NomeVeiculoLegal.Trim();
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[6].Value = l.VlThreshold;
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[7].Value = l.VlMTA;
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[8].Value = l.VlPrazo;
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[9].Value = l.PcHaircut;
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[10].Value = l.IdISDA;
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[11].Value = l.CdMoeda.Trim();

                                }
                                else if (listaCliente.Count(lc => ((lc.NomeCliente.Trim() == c.NomeCliente.Trim())
                                                             && (lc.NoCnpjCpf == c.NoCnpjCpf)
                                                             && (lc.IdVeiculoLegal == c.IdVeiculoLegal))) == 0)
                                {
                                    excelFile.Worksheets[0].Rows[contRowLayout].Cells[4].Value += "\n" + c.NomeCliente.Trim();
                                }


                                if (maxNomeCliente.Length < c.NomeCliente.Length)
                                    maxNomeCliente = c.NomeCliente;

                                listaCliente.Add(c);


                                //contRowMargem++;

                                //excelFile.Worksheets[1].Rows[contRowMargem].Cells[0].Value = l.dtPortfolio.ToString("dd/MM/yyyy");
                                //excelFile.Worksheets[1].Rows[contRowMargem].Cells[0].Value = l.IdISDA.ToString();
                                //excelFile.Worksheets[1].Rows[contRowMargem].Cells[1].Value = l.VlMargem;


                            }


                        });

                   
                    //Gera contratos ISDA de acordo com lista de clientes
                    List<Portfolio> listISDA = new List<Portfolio>();

                    _listaPortfolio.ForEach(l =>
                    {
                        listaCliente = new List<PortfolioCliente>();

                        foreach (var c in l.ListaClientes)
                        {
                            if (listaCliente.Count(lc => (lc.NoCnpjCpf == c.NoCnpjCpf)
                                                         && (lc.IdVeiculoLegal == c.IdVeiculoLegal)) == 0)
                            {
                                listaCliente = new List<PortfolioCliente>();
                                listISDA.Add(l);

                            }
                        }
                    }
                            );


                    //Remove contratos ISDA duplicados
                    Int32 index = 0;
                    while (index < listISDA.Count - 1)
                    {

                        if (listISDA[index].IdISDA.Value == listISDA[index + 1].IdISDA.Value)
                        {
                            listISDA.RemoveAt(index);
                            index = 0;
                        }
                        else
                            index++;


                    }

                    foreach (var item in listISDA)
                    {
                        contRowMargem++;

                        excelFile.Worksheets[1].Rows[contRowMargem].Cells[0].Value = item.IdISDA.ToString();
                        excelFile.Worksheets[1].Rows[contRowMargem].Cells[1].Value = item.VlMargem;

                    }


                   

                    foreach (var item in excelFile.Worksheets[0].Rows)
                        item.CellFormat.Font.Name = "Calibri";

                    foreach (var item in excelFile.Worksheets[1].Rows)
                        item.CellFormat.Font.Name = "Calibri";

                    excelFile.Worksheets[0].Rows[0].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
                    excelFile.Worksheets[1].Rows[0].CellFormat.Font.Bold = ExcelDefaultableBoolean.True;


                    excelFile.Worksheets[0].Columns[4].Width = Convert.ToInt32(maxNomeCliente.Length * 275);
                    excelFile.Worksheets[0].Columns[4].CellFormat.WrapText = ExcelDefaultableBoolean.True;

                    excelFile.Worksheets[0].Columns[0].Width = 16 * 275;
                    excelFile.Worksheets[0].Columns[1].Width = 16 * 275;



                    excelFile.Worksheets[0].Columns[0].CellFormat.FormatString = "dd/MM/yyyy";
                    excelFile.Worksheets[0].Columns[1].CellFormat.FormatString = "dd/MM/yyyy";

                    MessageBoxHelper.ShowSucess("Sucesso!", "Portfólio(s) exportado(s) com sucesso!");

                    this.Close();
                }
                else
                {
                    MessageBoxHelper.ShowExclamation("Atenção!", "Não existe(m) portfólio(s) para a Data de Vigência selecionada!");
                }

                excelFile.Save(_stream);
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowErro("Atenção!", "Erro ao executar o metodo ExportarPortfolios!", ex.Message);
            }
            finally
            {
                EndBusy();
                _stream.Close();
            }
        }

        private void btnCancelar()
        {
            this.Close();
        }

        private void dpDtBase_KeyUp(object sender, KeyEventArgs e)
        {
            if (dpDtBase.SelectedDate == null)
                dpDtBase.SelectedDate = DateTime.Now.Date;

            dpDtBase.Text = dpDtBase.SelectedDate.Value.Date.ToShortDateString();
        }

        private void dpDtBase_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            barraMenu.AlterarVisibilidadeBotao(Constantes.SourceImagem.BOTAO_APROVAR, true);
        }

        private void StartBusy()
        {
            activity.IsBusy = true;
            activity.BusyContent = "Exportando ...";
        }

        private void EndBusy()
        {
            activity.IsBusy = false;
        }

        #endregion

    }

}

